#!/bin/bash
set -e

# 停止已运行的服务
pkill -f backend/app.py || true
pkill -f "http.server" || true
sleep 1

# 激活虚拟环境
if [ -d ".venv" ]; then
  source .venv/bin/activate
fi

# 加载环境变量
source .env

# 启动后端
nohup python3 backend/app.py > backend.log 2>&1 &
BACKEND_PID=$!
echo "后端已启动，PID: $BACKEND_PID"

# 启动前端静态服务器
cd frontend
nohup python3 -m http.server 8000 > ../frontend.log 2>&1 &
FRONTEND_PID=$!
cd ..
echo "前端已启动，PID: $FRONTEND_PID"

sleep 2

# 自动打开浏览器
if which open > /dev/null; then
  open http://localhost:8000
elif which xdg-open > /dev/null; then
  xdg-open http://localhost:8000
else
  echo "请手动打开 http://localhost:8000"
fi